//
//  LoginViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/17.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "TTTAttributedLabel.h"

#import "UIButton+CountDown.h"
#import <ShareSDK/ShareSDK.h>
#import <AlipaySDK/AlipaySDK.h>
#import "TTUDIDManager.h"
#import "NSString+Hash.h"
#import "OpenInstallSDK.h"

#import "LoginHandleModel.h"

#import "PhoneSmsLoginView.h"
#import "PhonePswLoginView.h"
#import "SmsCodeInputView.h"
#import "BottomExchangeView.h"

#import "GradualChangeTransition.h"

#import "ForgetPswViewController.h"
#import "BindPhoneNumViewController.h"
#import "TT_WebviewController.h"

#import "BA_BusinessHelper.h"

#import "LoginViewController.h"

@interface LoginViewController ()<UIViewControllerTransitioningDelegate,TTTAttributedLabelDelegate>

@property (nonatomic, strong) GradualChangeTransition * transitionAnimation;

@property (weak, nonatomic) IBOutlet UIImageView *loginBGImageView;


@property (weak, nonatomic) IBOutlet UIView *inputBGView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputHeight;

@property (weak, nonatomic) IBOutlet UIView *exchangeBGView;


@property (weak, nonatomic) IBOutlet UILabel *titleLab;

@property (weak, nonatomic) IBOutlet UIView *privacyBGView;

@property (nonatomic, strong) LoginHandleModel *handleModel;


@property (nonatomic, strong) PhoneSmsLoginView *PhoneSmsView;
@property (nonatomic, strong) PhonePswLoginView *PhonePswView;
@property (nonatomic, strong) SmsCodeInputView *SmsCodeView;
@property (nonatomic, strong) BottomExchangeView *ExchangeView;

@property (nonatomic, strong) NSMutableArray *stepArray;


@end

@implementation LoginViewController

- (instancetype)init{
    
    if (self == [super init]) {
        self.transitionAnimation.transitionType = BA_TransitionOneType_Push;
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.type = TT_LoginType_PassWord;
    [self prepareData];
    [self initView];
}

- (void)prepareData {
    self.handleModel = [[LoginHandleModel alloc] init];
    self.handleModel.alias = [TTUDIDManager getUniqueDeviceID];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(request_WXAuth) name:@"BA_marryOauth" object:nil];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BA_marryOauth" object:nil];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)initView {
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    
    TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
    label.delegate = self;
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = UIColorHex(0x999999);
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 0;
    label.text = @"未注册婚前婚后账号的手机号，登录时将自动注册，且代表您已同意我们的《用户协议》和《隐私保护》";
    NSString *text = @"未注册婚前婚后账号的手机号，登录时将自动注册，且代表您已同意我们的《用户协议》和《隐私保护》";
    NSRange xieyiRange = [text rangeOfString:@"《用户协议》"];
    NSRange yinsiRange = [text rangeOfString:@"《隐私保护》"];

    label.linkAttributes = @{ (id)kCTForegroundColorAttributeName: UIColorHex(0xffffff),
                              (id)kCTUnderlineStyleAttributeName : [NSNumber numberWithInt:NSUnderlineStyleNone] };
    
    
    
    [label addLinkToURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BA_GlobalPdf_Domain, kUserPdf]] withRange:xieyiRange];
    [label addLinkToURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BA_GlobalPdf_Domain, kSecretPdf]] withRange:yinsiRange];
    
    [self.privacyBGView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(0);
    }];
        
    NSString *newVersion = [[NSUserDefaults standardUserDefaults] valueForKey:@"BA_version"];
    NSString *locationVersion = APP_VERSION;

    NSComparisonResult result = [locationVersion compare:newVersion];
        switch (result) {
            case NSOrderedAscending: {
                //上升
                NSLog(@"非审核状态-版本低");
                self.threeLoginBG.hidden = NO;
                
            case NSOrderedSame: {
                NSLog(@"非审核状态-版本一致");
                self.threeLoginBG.hidden = NO;

            } break;
            case NSOrderedDescending: {
                NSLog(@"审核状态");
                //隐藏一些东西
                self.threeLoginBG.hidden = YES;
            } break;
            default: {
                
            } break;
        }
    }
    
    [self configPhoneSmsView];
    [self configExchangeView];
    [self.loginBGImageView setImage:[UIImage imageNamed:self.model.bgImageUrl]];
    
    WEAKSELF
    self.ExchangeView.BottomExchangeViewBlock = ^(BottomExchangeActionType type) {
      
        switch (type) {
            case BottomExchangeActionType_exchange:{
                
                switch (weakSelf.type) {
                    case TT_LoginType_Code:{
                        [weakSelf configPhonePswView];
                    } break;
                    case TT_LoginType_PassWord:{
                        [weakSelf configPhoneSmsView];
                    } break;
                    default:
                        break;
                }
            } break;
            case BottomExchangeActionType_forgetPsw:{
                
                ForgetPswViewController *vc = [[ForgetPswViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            default:
                break;
        }
    };
    
    self.PhoneSmsView.PhoneSmsLoginViewBlock = ^(PhoneSmsActionType type) {
      
        switch (type) {
            case PhoneSmsActionType_getCode:{
                [weakSelf configRecSmsView];
            } break;
                
            default:
                break;
        }
    };
    
    self.PhonePswView.PhonePswLoginViewBlock = ^(PhonePswActionType type) {
        
        switch (type) {
            case PhonePswActionType_login:{
                [weakSelf request_login];
            } break;
                
            default:
                break;
        }
    };
    
    self.SmsCodeView.SmsCodeInputViewBlock = ^(SmsCodeInputActionType type, NSString *text) {
        
        switch (type) {
            case SmsCodeInputActionType_code:{
                [weakSelf request_loginSms];
            } break;
            case SmsCodeInputActionType_handleCode:{
                
                weakSelf.handleModel.VCode = text;
                [weakSelf request_login];
                
            } break;
            default:
                break;
        }
    };
    
    [[RACSignal merge:@[self.PhonePswView.phoneTF.rac_textSignal, RACObserve(self.PhonePswView.phoneTF, text)]] subscribeNext:^(NSString* text){
        self.handleModel.mobile = text;
    }];
    
    [[RACSignal merge:@[self.PhonePswView.pswTF.rac_textSignal, RACObserve(self.PhonePswView.pswTF, text)]] subscribeNext:^(NSString* text){
        self.handleModel.passWord = text;
    }];
    
    [[RACSignal merge:@[self.PhoneSmsView.phoneTF.rac_textSignal, RACObserve(self.PhonePswView.phoneTF, text)]] subscribeNext:^(NSString* text){
        self.handleModel.mobile = text;
    }];
}

- (void)attributedLabel:(__unused TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    [[BA_BusinessHelper shared] callSimpleWebWith:url.absoluteString htmlStr:@""];
}

- (void)clearView {
    
    [self.PhonePswView removeFromSuperview];
    [self.PhoneSmsView removeFromSuperview];
    [self.SmsCodeView removeFromSuperview];
}

- (void)configPhonePswView {
    [self clearView];
    
    [self.inputBGView addSubview:self.PhonePswView];
    [self.PhonePswView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    self.inputHeight.constant = [PhonePswLoginView calculateHeight];
    if (![self.stepArray containsObject:@(TT_LoginStepType_phonePsw)]) {
        [self.stepArray addObject:@(TT_LoginStepType_phonePsw)];
    }
    self.type = TT_LoginType_PassWord;
    self.titleLab.text = @"账号密码登录";
    [self.ExchangeView.exchangeBtn setTitle:@"手机号快速登录" forState:UIControlStateNormal];
    self.PhonePswView.phoneTF.text = self.handleModel.mobile;
    self.ExchangeView.hidden = NO;
}

- (void)configPhoneSmsView {
    [self clearView];
    
    [self.inputBGView addSubview:self.PhoneSmsView];
    [self.PhoneSmsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    self.inputHeight.constant = [PhoneSmsLoginView calculateHeight];
    
    if (![self.stepArray containsObject:@(TT_LoginStepType_phoneSms)]) {
        [self.stepArray addObject:@(TT_LoginStepType_phoneSms)];
    }
    
    self.type = TT_LoginType_Code;
    self.titleLab.text = @"手机号快速登录";
    [self.ExchangeView.exchangeBtn setTitle:@"账号密码登录" forState:UIControlStateNormal];
    self.PhoneSmsView.phoneTF.text = self.handleModel.mobile;
    self.ExchangeView.hidden = NO;
}

- (void)configRecSmsView {
    [self clearView];
    
    [self.inputBGView addSubview:self.SmsCodeView];
    [self.SmsCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    self.inputHeight.constant = [SmsCodeInputView calculateHeight];
    
    if (![self.stepArray containsObject:@(TT_LoginStepType_recSms)]) {
        [self.stepArray addObject:@(TT_LoginStepType_recSms)];
    }
    self.type = TT_LoginType_Code;
    self.titleLab.text = @"手机号快速登录";
    self.SmsCodeView.titleLab.text = [NSString stringWithFormat:@"验证码已发送至%@",self.handleModel.mobile];
    self.ExchangeView.hidden = YES;
    [self request_loginSms];
}

- (void)configExchangeView {
    
    [self.exchangeBGView addSubview:self.ExchangeView];
    [self.ExchangeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
}

#pragma mark 返回按钮
- (IBAction)closeAction:(id)sender {
    
    if (self.stepArray.count > 1) {
        [self.stepArray removeLastObject];
        [self configPhoneSmsView];
    } else {
        //先判断步骤数组里面最后一条数据
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark 微信登录
- (IBAction)wechatLoginAction:(id)sender {
    if (![WXApi isWXAppInstalled]) {
        [Utilities showToast:@"手机未安装微信"];
        return;
    }
    //构造SendAuthReq结构体
    SendAuthReq* req = [[SendAuthReq alloc]init];
    req.scope = S.scope_weixin;
    req.state = S.state_weixin;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req completion:nil];    
}

- (PhoneSmsLoginView *)PhoneSmsView {
    if (!_PhoneSmsView) {
        _PhoneSmsView = [[NSBundle mainBundle] loadNibNamed:@"PhoneSmsLoginView"owner:nil options:nil].firstObject;
    }
    return _PhoneSmsView;
}

- (PhonePswLoginView *)PhonePswView {
    if (!_PhonePswView) {
        _PhonePswView = [[NSBundle mainBundle] loadNibNamed:@"PhonePswLoginView"owner:nil options:nil].firstObject;
    }
    return _PhonePswView;
}

- (SmsCodeInputView *)SmsCodeView {
    if (!_SmsCodeView) {
        _SmsCodeView = [[NSBundle mainBundle] loadNibNamed:@"SmsCodeInputView"owner:nil options:nil].firstObject;
    }
    return _SmsCodeView;
}

- (BottomExchangeView *)ExchangeView {
    if (!_ExchangeView) {
        _ExchangeView = [[NSBundle mainBundle] loadNibNamed:@"BottomExchangeView"owner:nil options:nil].firstObject;
    }
    return _ExchangeView;
}



//返回处理push/pop动画过渡的对象
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC{
    
    if (operation == UINavigationControllerOperationPush) {
        self.transitionAnimation.transitionType = BA_TransitionOneType_Push;
        return self.transitionAnimation;
    }else if (operation == UINavigationControllerOperationPop){
        self.transitionAnimation.transitionType = BA_TransitionOneType_Pop;
    }
    return self.transitionAnimation;
}

- (GradualChangeTransition *)transitionAnimation {
    if (_transitionAnimation == nil) {
        _transitionAnimation = [[GradualChangeTransition alloc] init];
    }
    return _transitionAnimation;
}

- (NSMutableArray *)stepArray {
    if (!_stepArray) {
        _stepArray = @[].mutableCopy;
    }
    return _stepArray;
}

- (void)request_WXAuth {
    NSString *code = [Utilities getFromNSUserDefaults:@"BA_marryOauth"];
    [self request_thirdAuthWithType:SelPayMethodType_wechat code:code];
}

#pragma mark 支付宝拿到authcode  微信拿到code后请求这个接口，检查是否在平台绑定过
- (void)request_thirdAuthWithType:(SelPayMethodType)type code:(NSString *)code{
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:code forKey:@"code"];
    [dic setValue:[TTUserModel sharedObject].installModel.myCode forKey:@"myCode"];
    [dic setValue:@"1" forKey:@"sourceType"];

    switch (type) {
        case SelPayMethodType_wechat:{
            [dic setValue:@"wx" forKey:@"type"];
        } break;
        case SelPayMethodType_alipay:{
            [dic setValue:@"ali" forKey:@"type"];
        } break;
        default:
            break;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Platform,API_ThirdAuth];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]] && [resultDic.allKeys containsObject:@"token"]) {
                    
                    NSString *token = [resultDic valueForKey:@"token"];

                    NSMutableDictionary *user = [resultDic valueForKey:@"user"];
                    [[TTUserModel sharedObject].userModelDefault setValue:token forKey:@"TT_token"];
                    
                    BOOL isNewer = [[resultDic valueForKey:@"isNewer"] boolValue];
                    [[TTUserModel sharedObject].userModelDefault setValue:isNewer?@"1":@"0" forKey:@"TT_isNewer"];

                    [[TTUserModel sharedObject].userModelDefault synchronize];
                    [[TTUserModel sharedObject] fillUserModelWithDic:user];
                    
                    if (weakSelf.completion) {
                        weakSelf.completion(YES, resultDic);
                    }
                    
                    [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    NSDictionary *wxUserInfo = [resultDic valueForKey:@"wxUserInfo"];
                    BindPhoneNumViewController *vc = [[BindPhoneNumViewController alloc] init];
                    vc.completion = ^(BOOL isLogin, NSDictionary * _Nonnull options) {
                      
                        if (weakSelf.completion) {
                            weakSelf.completion(isLogin, options);
                        }
                    };
                    
                    switch (type) {
                        case SelPayMethodType_wechat:{
                            vc.openid = [wxUserInfo valueForKey:@"openid"];
                        } break;
                        case SelPayMethodType_alipay:{
                            vc.aliId = [resultDic valueForKey:@"aliId"];
                        } break;
                        default:
                            break;
                    }
                    
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }

            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {

        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}

#pragma mark 账号密码登录login
- (void)request_login {

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.handleModel.mobile forKey:@"userName"];
    [dic setValue:self.handleModel.alias forKey:@"alias"];

    [dic setValue:@"4" forKey:@"loginType"];
    [dic setValue:[TTUserModel sharedObject].installModel.myCode forKey:@"myCode"];

    if (self.type == TT_LoginType_Code) {
        [dic setValue:self.handleModel.VCode forKey:@"vcode"];
    } else {
        
        [dic setValue:self.handleModel.passWord forKey:@"passWord"];
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Platform,API_Login_V2];
    
WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                NSString *token = [resultDic valueForKey:@"token"];
                NSMutableDictionary *user = [resultDic valueForKey:@"user"];
                
                [[TTUserModel sharedObject].userModelDefault setValue:token forKey:@"TT_token"];
                
                BOOL isNewer = [[resultDic valueForKey:@"isNewer"] boolValue];
                [[TTUserModel sharedObject].userModelDefault setValue:isNewer?@"1":@"0" forKey:@"TT_isNewer"];
                
                BOOL isRegister = [[resultDic valueForKey:@"isRegister"] boolValue];
                if (isRegister) {
                    [OpenInstallSDK reportRegister];
                    [TTUserModel sharedObject].isRegister = YES;
                }
                
                [[TTUserModel sharedObject].userModelDefault synchronize];
                [[TTUserModel sharedObject] fillUserModelWithDic:user];

                if (weakSelf.completion) {
                    weakSelf.completion(YES, resultDic);
                }
                
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];

            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}


- (void)request_loginSms {

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.handleModel.mobile forKey:@"mobile"];
    [dic setValue:@"2" forKey:@"type"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SMS];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [weakSelf.SmsCodeView.countDownBtn startWithTime:59
                                           title:@"重新发送"
                                  countDownTitle:@"s"
                                       mainColor:UIColor.clearColor
                                      countColor:UIColor.clearColor];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {

        [SVProgressHUD showErrorWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];

    }];
}

@end
